﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Workflow.Runtime;
using System.Workflow.ComponentModel;
using Openfree.Workflow.Common;
using Openfree.Workflow.Activities;

public partial class PMSWeb_WFQingJia : PMSBase
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ProcessList1.OnProcessed += new EventHandler(On_ProcessedSelectRole);
        ProcessList1.OnCancel += new EventHandler(On_CancelSelectRole);
        ProcessList2.OnProcessed += new EventHandler(On_ProcessedSelectRole);
        ProcessList2.OnCancel += new EventHandler(On_CancelSelectRole);

        if (!IsPostBack)
        {
            string categoryCode = Request["CategoryCode"];
            string doAction = Request["Do"];
            hfInstanceID.Value = Request["InstanceID"];
            
            if (!string.IsNullOrEmpty(categoryCode))
            {
                //初始化下拉列表和工作流名称等基本信息
                string cmdText = @"select a.*, b.CodeName GroupCodeName from T_WorkflowCategory a 
                right join T_CodeConfig b on a.GroupCode=b.CodeValue where 
                b.Category='WorkflowGroup' and a.CategoryCode='{0}' order by OrderIndex";
                DataSet ds = BaseAccess.GetDataSet(base.Connection, string.Format(cmdText, categoryCode));

                literalSubject.Text = ds.Tables[0].Rows[0]["GroupCodeName"].ToString() + "."
                        + ds.Tables[0].Rows[0]["Subject"].ToString()
                        + "&nbsp;&nbsp;-&nbsp;&nbsp"
                        + SessionManager.Username + " ["
                        + UserAccess.GetUserOrgName(base.Connection, SessionManager.UserID) + "]";
                literalSubject2.Text = literalSubject.Text;
                ViewState["CategoryCode"] = categoryCode;
                if (string.IsNullOrEmpty(Request.UrlReferrer.Query.ToString()))
                {
                    ViewState["UrlReferrer"] = Request.UrlReferrer.ToString();
                }
                else
                {
                    ViewState["UrlReferrer"] = Request.UrlReferrer.ToString().Replace(Request.UrlReferrer.Query.ToString(), "");
                }
                InitBaseDate();
                ProcessList2.Visible = false;
                
                //修改初始化业务数据
                if (!string.IsNullOrEmpty(hfInstanceID.Value))
                {
                    cmdText = @"select a.*, 
                    (select Username from T_User where UserID=a.UserID) Username,
                    (select top 1 CodeName from T_CodeConfig where GroupCode=b.GroupCode and Category='WorkflowGroup') GroupCodeName,
                    b.Subject CategorySubject,
                    b.ActivityPage
                    from T_Workflow a left join T_WorkflowCategory b 
                    on a.CategoryCode=b.CategoryCode where a.InstanceID='{0}'";
                    ds = BaseAccess.GetDataSet(base.Connection, string.Format(cmdText, hfInstanceID.Value));
                    DataRow row = ds.Tables[0].Rows[0];

                    if (!string.IsNullOrEmpty(doAction))
                    {
                        //todo 需要判断流程是否完成，是否可以继续提交
                        if ("Edit".Equals(doAction))
                        {
                            //WorkflowOwner.aspx 页面提交
                            InitEditData(hfInstanceID.Value, row);
                        }

                        //todo 需要判断流程是否完成，是否可以继续提交
                        if ("Submit".Equals(doAction))
                        {
                            //WorkflowOwner.aspx 直接提交
                            InitEditData(hfInstanceID.Value, row);
                            ViewState["_instanceID"] = hfInstanceID.Value;
                            Save(true);
                        }

                        if ("View".Equals(doAction))
                        {
                            InitViewData(hfInstanceID.Value, row);
                        }
                    }
                }
            }
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        Save(false);
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        Save(true);
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect(ViewState["UrlReferrer"].ToString());
    }

    protected virtual void On_ProcessedSelectRole(object sender, EventArgs e)
    {
        Response.Redirect(ViewState["UrlReferrer"].ToString() + "?Do=Submit");
    }

    protected virtual void On_CancelSelectRole(object sender, EventArgs e)
    {
        Response.Redirect(ViewState["UrlReferrer"].ToString());
    }


    /// <summary>
    /// 
    /// </summary>
    /// <param name="isSubmit">决定是否选择相应审批人</param>
    private void Save(Boolean isSubmit)
    {
        if (string.IsNullOrEmpty(tbSjDay.Text.Trim())) tbSjDay.Text = "0";
        if (string.IsNullOrEmpty(tbBjDay.Text.Trim())) tbBjDay.Text = "0";
        if (string.IsNullOrEmpty(tbNjDay.Text.Trim())) tbNjDay.Text = "0";
        if (string.IsNullOrEmpty(tbQtjDay.Text.Trim())) tbQtjDay.Text = "0";
        if (string.IsNullOrEmpty(tbJbdxDay.Text.Trim())) tbJbdxDay.Text = "0";
        if (string.IsNullOrEmpty(tbZbdxDay.Text.Trim())) tbZbdxDay.Text = "0";

        string processActivity = string.Empty;
        string instanceID = hfInstanceID.Value;
        if (string.IsNullOrEmpty(instanceID))
        {
            //add
            instanceID = WorkflowManager.AddWorkflow(typeof(QingJia), isSubmit, ddlSelectRole.SelectedValue);
            //AddWorkflow 之后需要有一定延迟，才能获取最新状态
            System.Threading.Thread.Sleep(1000);
            processActivity = WorkflowManager.GetActivityState(new Guid(instanceID));

            DataSet ds = BaseAccess.GetDataSet(base.Connection, "select * from T_Workflow where 1=2", "T_Workflow");
            BaseAccess.FillDataSet(base.Connection, ds, "select * from WF_QingJia where 1=2", "WF_QingJia");

            DataRow rowWorkflow = ds.Tables["T_Workflow"].NewRow();
            rowWorkflow["InstanceID"] = instanceID;
            rowWorkflow["Subject"] = tbSubject.Text.Trim();
            rowWorkflow["CategoryCode"] = ViewState["CategoryCode"].ToString();
            rowWorkflow["UserID"] = SessionManager.UserID;
            rowWorkflow["CreateDate"] = DateTime.Now;
            rowWorkflow["StartDate"] = DateTime.Now;
            rowWorkflow["CurrentState"] = WorkflowStatus.Running;
            rowWorkflow["IsSubmit"] = 0;
            rowWorkflow["ProcessActivity"] = processActivity;
            ds.Tables["T_Workflow"].Rows.Add(rowWorkflow);

            DataRow rowQJ = ds.Tables["WF_QingJia"].NewRow();
            rowQJ["InstanceID"] = instanceID;
            rowQJ["UserID"] = SessionManager.UserID;
            rowQJ["BeginDate"] = tbBeginDate.Text.Trim() + " " + ddlBeginHH.SelectedValue + ":" + ddlBeginMM.SelectedValue;
            rowQJ["SjDay"] = tbSjDay.Text.Trim();
            rowQJ["BjDay"] = tbBjDay.Text.Trim();
            rowQJ["NjDay"] = tbNjDay.Text.Trim();
            rowQJ["QtjDay"] = tbQtjDay.Text.Trim();
            rowQJ["JbdxDay"] = tbJbdxDay.Text.Trim();
            rowQJ["ZbdxDay"] = tbZbdxDay.Text.Trim();
            rowQJ["Leaved"] = rbListLeaved.SelectedValue;
            rowQJ["WhereTo"] = tbWhereTo.Text.Trim();
            rowQJ["IsCar"] = cbIsCar.Checked;
            rowQJ["IsTrain"] = cbIsTrain.Checked;
            rowQJ["IsShip"] = cbIsShip.Checked;
            rowQJ["IsAircraft"] = cbIsAircraft.Checked;
            if (string.IsNullOrEmpty(tbLeaveDate.Text.Trim()))
            {
                rowQJ["LeaveDate"] = DBNull.Value;
            }
            else
            {
                rowQJ["LeaveDate"] = tbLeaveDate.Text.Trim() + " " + ddlLeaveHH.SelectedValue + ":" + ddlLeaveMM.SelectedValue;

            }
            if (string.IsNullOrEmpty(tbBackDate.Text.Trim()))
            {
                rowQJ["BackDate"] = DBNull.Value;
            }
            else
            {
                rowQJ["BackDate"] = tbBackDate.Text.Trim() + " " + ddlBackHH.SelectedValue + ":" + ddlBackMM.SelectedValue;
            }
            rowQJ["Description"] = tbDescription.Text.Trim();
            ds.Tables["WF_QingJia"].Rows.Add(rowQJ);

            BaseAccess.UpdateDataSet(base.Connection, new string[] { "T_Workflow", "WF_QingJia" }, ds);
        }
        else
        {
            //edit
            DataSet ds = BaseAccess.GetDataSet(base.Connection,
                string.Format("select * from T_Workflow where InstanceID='{0}'", instanceID), "T_Workflow");
            BaseAccess.FillDataSet(base.Connection, ds,
                string.Format("select * from WF_QingJia where InstanceID='{0}'", instanceID), "WF_QingJia");

            DataRow rowWorkflow = ds.Tables["T_Workflow"].Rows[0];
            if(tbSubject.Text.Trim() != string.Empty) rowWorkflow["Subject"] = tbSubject.Text.Trim();
            rowWorkflow["StartDate"] = DateTime.Now;
            rowWorkflow["CurrentState"] = WorkflowStatus.Running;

            processActivity = WorkflowManager.GetActivityState(new Guid(instanceID));
            if (isSubmit && processActivity == "InitialState")
            {
                //ascx所在的页面不同，入口不一样，所以Edit时需要判断一下当前的ActivityState
                WorkflowManager.RaiseApproveEvent(new Guid(instanceID), null);
                //AddWorkflow 之后需要有一定延迟，才能获取最新状态
                System.Threading.Thread.Sleep(1000);
                processActivity = WorkflowManager.GetActivityState(new Guid(instanceID));
                rowWorkflow["ProcessActivity"] = processActivity;
            }


            DataRow rowQJ = ds.Tables["WF_QingJia"].Rows[0];
            rowQJ["BeginDate"] = tbBeginDate.Text.Trim() + " " + ddlBeginHH.SelectedValue + ":" + ddlBeginMM.SelectedValue;
            rowQJ["SjDay"] = tbSjDay.Text.Trim();
            rowQJ["BjDay"] = tbBjDay.Text.Trim();
            rowQJ["NjDay"] = tbNjDay.Text.Trim();
            rowQJ["QtjDay"] = tbQtjDay.Text.Trim();
            rowQJ["JbdxDay"] = tbJbdxDay.Text.Trim();
            rowQJ["ZbdxDay"] = tbZbdxDay.Text.Trim();
            rowQJ["Leaved"] = rbListLeaved.SelectedValue;
            rowQJ["WhereTo"] = tbWhereTo.Text.Trim();
            rowQJ["IsCar"] = cbIsCar.Checked;
            rowQJ["IsTrain"] = cbIsTrain.Checked;
            rowQJ["IsShip"] = cbIsShip.Checked;
            rowQJ["IsAircraft"] = cbIsAircraft.Checked;
            if (string.IsNullOrEmpty(tbLeaveDate.Text.Trim()))
            {
                rowQJ["LeaveDate"] = DBNull.Value;
            }
            else
            {
                rowQJ["LeaveDate"] = tbLeaveDate.Text.Trim() + " " + ddlLeaveHH.SelectedValue + ":" + ddlLeaveMM.SelectedValue;

            }
            if (string.IsNullOrEmpty(tbBackDate.Text.Trim()))
            {
                rowQJ["BackDate"] = DBNull.Value;
            }
            else
            {
                rowQJ["BackDate"] = tbBackDate.Text.Trim() + " " + ddlBackHH.SelectedValue + ":" + ddlBackMM.SelectedValue;
            }
            rowQJ["Description"] = tbDescription.Text.Trim();


            BaseAccess.UpdateDataSet(base.Connection, new string[] { "T_Workflow", "WF_QingJia" }, ds);
        }

        if (isSubmit)
        {
            webPanelButtonArea.Visible = false;
            ProcessList2.Visible = true;
            ProcessList2.InitGridViewSelect(instanceID, processActivity);
        }
        else
        {
            Response.Redirect(ViewState["UrlReferrer"].ToString()+"?Do=Save");
        }
    }

    
    private void ClearValue()
    {
        tbSubject.Text = "";
        tbBeginDate.Text = "";
        tbSjDay.Text = "";
        tbBjDay.Text = "";
        tbNjDay.Text = "";
        tbQtjDay.Text = "";
        tbJbdxDay.Text = "";
        tbZbdxDay.Text = "";
        rbListLeaved.SelectByValue = "0";
        tbWhereTo.Text = "";
        cbIsCar.Checked = false;
        cbIsTrain.Checked = false;
        cbIsShip.Checked = false;
        cbIsAircraft.Checked = false;
        tbLeaveDate.Text = "";
        ddlLeaveHH.SelectedIndex = 0;
        ddlLeaveMM.SelectedIndex = 0;
        tbBackDate.Text = string.Empty;
        ddlBackHH.SelectedIndex = 0;
        ddlBackMM.SelectedIndex = 0;
        tbDescription.Text = "";
    }

    private void InitBaseDate()
    {
        ddlBeginHH.Items.Clear();
        ddlLeaveHH.Items.Clear();
        ddlBackHH.Items.Clear();
        for (int i = 0; i < 24; i++)
        {
            ddlBeginHH.Items.Add(new ListItem(i.ToString() + "时", i.ToString("00")));
            ddlLeaveHH.Items.Add(new ListItem(i.ToString() + "时", i.ToString("00")));
            ddlBackHH.Items.Add(new ListItem(i.ToString() + "时", i.ToString("00")));

        }
        ddlBeginMM.Items.Clear();
        ddlLeaveMM.Items.Clear();
        ddlBackMM.Items.Clear();
        for (int i = 0; i < 60; i++)
        {
            ddlBeginMM.Items.Add(new ListItem(i.ToString() + "分", i.ToString("00")));
            ddlLeaveMM.Items.Add(new ListItem(i.ToString() + "分", i.ToString("00")));
            ddlBackMM.Items.Add(new ListItem(i.ToString() + "分", i.ToString("00")));
        }

        ddlSelectRole.Items.Clear();
        SecurityAccess securityAccess = new SecurityAccess(base.Connection);
        DataSet ds = securityAccess.LoadPermission(SessionManager.UserID);
        if (ds.Tables[0].Rows.Count > 0)
        {
            foreach (DataRow row in ds.Tables[0].Select("Category='审批角色'", "OrderIndex desc"))
            {
                ListItem item = new ListItem();
                item.Text = row["Subject"].ToString();
                item.Value = row["Description"].ToString();
                ddlSelectRole.Items.Add(item);
            }
        }
        else
        {
            trSelectRole.Visible = false;
        }
        ddlSelectRole.Items.Insert(0, new ListItem("普通员工", ""));
    }

    public void InitViewData(string instanceID, DataRow rowWorkflow)
    {
        lbLeaveDate.Text = string.Empty;
        lbBackDate.Text = string.Empty;

        string cmdText = "select * from WF_QingJia where InstanceID='{0}'";
        cmdText = string.Format(cmdText, instanceID);
        DataSet ds = BaseAccess.GetDataSet(base.Connection, cmdText);
        DataRow row = ds.Tables[0].Rows[0];

        lbSubject.Text = HttpUtility.HtmlEncode(rowWorkflow["Subject"].ToString());
        lbBeginDate.Text = Convert.ToDateTime(row["BeginDate"].ToString()).ToString("yyyy-MM-dd HH:mm");
        lbSjDay.Text = row["SjDay"].ToString();
        lbBjDay.Text = row["BjDay"].ToString();
        lbNjDay.Text = row["NjDay"].ToString();
        lbQtjDay.Text = row["QtjDay"].ToString();
        lbJbdxDay.Text = row["JbdxDay"].ToString();
        lbZbdxDay.Text = row["ZbdxDay"].ToString();
        rbListLeaved2.SelectByValue = row["Leaved"].ToString();
        lbWhereTo.Text = row["WhereTo"].ToString();
        cbIsCar2.Value = row["IsCar"].ToString();
        cbIsTrain2.Value = row["IsTrain"].ToString();
        cbIsShip2.Value = row["IsShip"].ToString();
        cbIsAircraft2.Value = row["IsAircraft"].ToString();
        if (!Convert.IsDBNull(row["LeaveDate"]))
        {
            lbLeaveDate.Text = Convert.ToDateTime(row["LeaveDate"].ToString()).ToString("yyyy-MM-dd HH:mm");
        }
        if (!Convert.IsDBNull(row["BackDate"]))
        {
            lbBackDate.Text = Convert.ToDateTime(row["BackDate"].ToString()).ToString("yyyy-MM-dd  HH:mm");
        }
        lbDescription.Text = HttpUtility.HtmlEncode(row["Description"].ToString()).Replace("\r\n", "<br />"); ;


        pnlEdit.Visible = false;
        pnlView.Visible = true;
        divCancelButton.Visible = true;
        trSelectRole.Visible = false;
        ProcessList2.Visible = false;
        ProcessList1.Visible = true;
        bool flag = ProcessList1.InitProcess(instanceID, true, true);
        divCancelButton.Visible = !flag;
    }

    private void InitEditData(string instanceID, DataRow rowWorkflow)
    {
        tbLeaveDate.Text = string.Empty;
        ddlLeaveHH.SelectedIndex = 0;
        ddlLeaveMM.SelectedIndex = 0;
        tbBackDate.Text = string.Empty;
        ddlBackHH.SelectedIndex = 0;
        ddlBackMM.SelectedIndex = 0;

        string cmdText = "select * from WF_QingJia where InstanceID='{0}'";
        cmdText = string.Format(cmdText, instanceID);
        DataSet ds = BaseAccess.GetDataSet(base.Connection, cmdText);
        DataRow rowQJ = ds.Tables[0].Rows[0];

        tbSubject.Text = rowWorkflow["Subject"].ToString();
        tbBeginDate.Text = Convert.ToDateTime(rowQJ["BeginDate"].ToString()).ToString("yyyy-MM-dd");
        ddlBeginHH.SelectByValue = Convert.ToDateTime(rowQJ["BeginDate"].ToString()).ToString("HH");
        ddlBeginMM.SelectByValue = Convert.ToDateTime(rowQJ["BeginDate"].ToString()).ToString("mm");
        tbSjDay.Text = rowQJ["SjDay"].ToString();
        tbBjDay.Text = rowQJ["BjDay"].ToString();
        tbNjDay.Text = rowQJ["NjDay"].ToString();
        tbQtjDay.Text = rowQJ["QtjDay"].ToString();
        tbJbdxDay.Text = rowQJ["JbdxDay"].ToString();
        tbZbdxDay.Text = rowQJ["ZbdxDay"].ToString();
        rbListLeaved.SelectByValue = rowQJ["Leaved"].ToString();
        tbWhereTo.Text = rowQJ["WhereTo"].ToString();
        cbIsCar.Value = rowQJ["IsCar"].ToString();
        cbIsTrain.Value = rowQJ["IsTrain"].ToString();
        cbIsShip.Value = rowQJ["IsShip"].ToString();
        cbIsAircraft.Value = rowQJ["IsAircraft"].ToString();
        if (!Convert.IsDBNull(rowQJ["LeaveDate"]))
        {
            tbLeaveDate.Text = Convert.ToDateTime(rowQJ["LeaveDate"].ToString()).ToString("yyyy-MM-dd");
            ddlLeaveHH.SelectByValue = Convert.ToDateTime(rowQJ["LeaveDate"].ToString()).ToString("HH");
            ddlLeaveMM.SelectByValue = Convert.ToDateTime(rowQJ["LeaveDate"].ToString()).ToString("mm");
        }
        if (!Convert.IsDBNull(rowQJ["BackDate"]))
        {
            tbBackDate.Text = Convert.ToDateTime(rowQJ["BackDate"].ToString()).ToString("yyyy-MM-dd");
            ddlBackHH.SelectByValue = Convert.ToDateTime(rowQJ["BackDate"].ToString()).ToString("HH");
            ddlBackMM.SelectByValue = Convert.ToDateTime(rowQJ["BackDate"].ToString()).ToString("mm");
        }
        tbDescription.Text = rowQJ["Description"].ToString();


        pnlEdit.Visible = true;
        pnlView.Visible = false;
        divCancelButton.Visible = false;
        trSelectRole.Visible = false;
        ProcessList1.Visible = false;
        ProcessList2.Visible = true;
        ProcessList2.InitProcess(instanceID, false, false);
    }
}